/**
 * 微信JSAPI统一下单
 * Created by Administrator on 2017/07/12
 *
 */

var request = require('request');
var crypto = require('crypto');
var fs = require('fs');
var userDao = require('../../dao/userDao');
var disUserDao = require('../../dao/disUserDao');

var wxPayConf = {
    appID: 'wxd44830a7fce3040d',
    mch_id:'1243223402',
    partnerSecret:'jinhua18mishang98touzi10guanli88',
    maSecret:'uaCxhZXFTjY2aHm7jIis7WcrSfo101Qd',
    notify_url:'http://weblogin.178dn.net/wxPaySign',
    disNotify_url:'http://weblogin.178dn.net/disWxPaySign',
    disMaNotify_url:'http://weblogin.178dn.net/disMaPaySign',
    disMaReturn_url:'http://disa.178dn.net/distribution/view/me.html'
};

//微信支付
exports.pay = function (req, res) {

    res.send({code:1,info:'支付暂未开启!'});
    return;

    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    var openid = req.headers.openid;
    var goodid = parseInt(req.headers.goodid);
    var sid = parseInt(req.headers.sid);

    var time_stamp = new Date().getTime();
    var ip = req.ipAddress;
    var bookingNo = getOrderId(goodid,sid)+time_stamp;
    //console.log('---sid:%s,ip:%s',sid,ip);
    var attach = 'test';
    var nonce_str = createNonceStr(15);
    //console.log(' \n 1. nonce_str: %s',nonce_str);
    var total_fee = goodConfi(goodid);
    //console.log('---goodid:%s,total_fee:%s',goodid,total_fee);
    //total_fee = 1;
    var body = '购买金币';
    var dataOpt = {
        appid: wxPayConf.appID,
        attach: attach,
        body: body,
        mch_id: wxPayConf.mch_id,
        nonce_str: nonce_str,
        notify_url:wxPayConf.notify_url,
        openid:openid,
        out_trade_no:bookingNo,
        spbill_create_ip:ip,
        total_fee:total_fee,
        trade_type:'JSAPI'
    };
    var formData = "<xml>";
    formData += "<appid>"+wxPayConf.appID+"</appid>"; //appid
    formData += "<attach>"+attach+"</attach>"; //附加数据
    formData += "<body>"+body+"</body>";
    formData += "<mch_id>"+wxPayConf.mch_id+"</mch_id>"; //商户号
    formData += "<nonce_str>"+nonce_str+"</nonce_str>"; //随机字符串，不长于32位。
    formData += "<notify_url>"+wxPayConf.notify_url+"</notify_url>";
    formData += "<openid>"+openid+"</openid>";
    formData += "<out_trade_no>"+bookingNo+"</out_trade_no>";
    formData += "<spbill_create_ip>"+ip+"</spbill_create_ip>";
    formData += "<total_fee>"+total_fee+"</total_fee>";
    formData += "<trade_type>JSAPI</trade_type>";
    formData += "<sign>"+wxSignMd5(dataOpt)+"</sign>";
    formData += "</xml>";
    //console.log('\n formData:',JSON.stringify(formData));
    request({url: url, method: 'POST', body: formData}, function (err, response, body) {

        if (!err && response.statusCode == 200) {
            //console.log(' \n res body:',body);
            var return_code = getXMLNodeValue('return_code', body.toString("utf-8")) || 'FALL';

            //console.log(' \n return_code:%s',return_code);
            if(return_code == 'FALL'){
                res.send({code:1,info:'支付失败!'});
                return;
            }
            var result_code = getXMLNodeValue('result_code', body.toString("utf-8")) || 'FALL';
            //console.log(' \n result_code:%s',result_code);
            if(result_code.indexOf('FALL') != -1){
                res.send({code:1,info:'支付失败!'});
                return;
            }

            var prepay_id = getXMLNodeValue('prepay_id', body.toString("utf-8"));
            var nonce_str = getXMLNodeValue('nonce_str', body.toString("utf-8"));
            //console.log(' \n 2.nonce_str:%s time_stamp:%s',nonce_str,time_stamp);
            //签名
            var _paySignjs = wxSignMd5({appId: wxPayConf.appID,nonceStr: nonce_str,package:'prepay_id='+prepay_id,signType:'MD5',timeStamp:time_stamp});

            //console.log('prepay_id:%s,_paySignjs: ',prepay_id,_paySignjs);
            res.send({code:0,prepay_id: prepay_id,_paySignjs:_paySignjs,nonce_str:nonce_str,time_stamp:time_stamp,coinNum:tradeConfi(total_fee)}); //res.render('jsapipay',{rows:body}); //res.redirect(tmp3[0]); } });
        }
    });
};

//微信发送红包
exports.sendPacket = function (req, res) {
    var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    var openid = req.headers.openid;
    var sid = req.headers.sid;
    var postCoin =parseInt(req.headers.postcoin);
    //对金币进行处理
    userDao.getUserById(openid,null,null, function (err,user) {
        if(err){
            res.send({code:1,info:'未知错误,请重试!'});
            return;
        }
        var userCoin = user.coin;
        if(postCoin>userCoin){
            res.send({code:1,info:'金币不足!'});
            return;
        }

        var ip = req.ipAddress;
        var mch_billno = createNonceStr(15);        //商户订单号
        //console.log('---opid:%s,ip:%s',openid,ip);
        var nonce_str = createNonceStr(15);
        //console.log(' \n 1. nonce_str: %s',nonce_str);
        var total_amount = cashConfi(postCoin);
        //total_amount = 100;
        var act_name = '抢红包';
        var send_name = '欢乐大转盘';
        var total_num = 1;
        //console.log('---total_num:%s',total_num);
        var remark = '转的越多,抢的越多哦';
        var wishing = '感谢您参加大转盘活动';
        var dataOpt = {wxappid:wxPayConf.appID,act_name:act_name,mch_id:wxPayConf.mch_id,mch_billno:mch_billno,nonce_str:nonce_str,re_openid:openid,send_name:send_name,client_ip:ip,total_amount:total_amount,total_num:total_num,remark:remark,wishing:wishing};
        var formData = "<xml>";
        formData += "<wxappid>"+wxPayConf.appID+"</wxappid>"; //appid
        formData += "<act_name>"+act_name+"</act_name>"; //活动名称
        formData += "<mch_id>"+wxPayConf.mch_id+"</mch_id>"; //商户号
        formData += "<mch_billno>"+mch_billno+"</mch_billno>"; //商户订单号
        formData += "<nonce_str>"+nonce_str+"</nonce_str>"; //随机字符串，不长于32位。
        formData += "<re_openid>"+openid+"</re_openid>";
        formData += "<send_name>"+send_name+"</send_name>";
        formData += "<client_ip>"+ip+"</client_ip>";
        formData += "<total_amount>"+total_amount+"</total_amount>";
        formData += "<total_num>"+total_num+"</total_num>";
        formData += "<remark>"+remark+"</remark>";        //备注
        formData += "<wishing>"+wishing+"</wishing>";        //备注
        formData += "<sign>"+wxSignMd5(dataOpt)+"</sign>";
        formData += "</xml>";
        request({url: url, method: 'POST',key: fs.readFileSync('./app/wechat/cert/apiclient_key.pem'),cert: fs.readFileSync('./app/wechat/cert/apiclient_cert.pem'), body: formData}, function (err, response, body) {

            if (!err && response.statusCode == 200) {
                console.log(' \n sendPacket body:',body);
                var return_code = getXMLNodeValue('return_code', body.toString("utf-8")) || 'FAIL';

                console.log(' \n sendPacket return_code:%s',return_code);
                if(return_code == 'FAIL'){
                    res.send({code:1,info:'提现失败!'});
                    return;
                }
                var result_code = getXMLNodeValue('result_code', body.toString("utf-8")) || 'FAIL';
                console.log(' \n sendPacket result_code:%s',result_code);
                if(result_code.indexOf('FAIL') != -1){
                    res.send({code:1,info:'提现失败!'});
                    return;
                }

                userDao.increaseUserCoin(openid,-postCoin, function (err) {
                    if(err){
                        res.send({code:1,info:'扣除金币失败,请重试!!'});
                        return;
                    }else {
                        userDao.recorderCash(sid,openid,mch_billno,postCoin,total_amount);
                        res.send({code:0}); //res.render('jsapipay',{rows:body}); //res.redirect(tmp3[0]); } });
                    }
                });
            }else {
                res.send({code:1,info:'提现失败,请重试!!'});
            }
        });
    });
};

//微信企业打款到零钱包
exports.transfers = function (req, res) {
    var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    var openid = req.headers.openid;
    var sid = req.headers.sid;
    var postCoin =parseInt(req.headers.postcoin);
    //对金币进行处理
    userDao.getUserById(openid,null,null, function (err,user) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
            return;
        }
        var userCoin = user.coin;
        if(postCoin>userCoin){
            res.send({code:1,info:'金币不足!'});
            return;
        }

        var ip = req.ipAddress;
        var mch_billno = createNonceStr(15);        //商户订单号
        //console.log('---opid:%s,ip:%s',openid,ip);
        var nonce_str = createNonceStr(15);
        //console.log(' \n 1. nonce_str: %s',nonce_str);
        var total_amount = cashConfi(postCoin);
        //total_amount = 100;
        var check_name = 'NO_CHECK';
        var desc = '发放奖励~~';
        var dataOpt = {mch_appid:wxPayConf.appID,mchid:wxPayConf.mch_id,nonce_str:nonce_str,partner_trade_no:mch_billno,openid:openid,check_name:check_name,amount:total_amount,desc:desc,spbill_create_ip:ip};
        var formData = "<xml>";
        formData += "<amount>"+total_amount+"</amount>";
        formData += "<check_name>"+check_name+"</check_name>";        //校验用户姓名选项
        formData += "<desc>"+desc+"</desc>";        //企业付款描述信息
        formData += "<mch_appid>"+wxPayConf.appID+"</mch_appid>"; //appid
        formData += "<mchid>"+wxPayConf.mch_id+"</mchid>"; //商户号
        formData += "<nonce_str>"+nonce_str+"</nonce_str>"; //随机字符串，不长于32位。
        formData += "<openid>"+openid+"</openid>";
        formData += "<partner_trade_no>"+mch_billno+"</partner_trade_no>"; //商户订单号
        formData += "<spbill_create_ip>"+ip+"</spbill_create_ip>";
        formData += "<sign>"+wxSignMd5(dataOpt)+"</sign>";
        formData += "</xml>";
        //console.log('0 formData:%s \n',formData);
        request({url: url, method: 'POST',key: fs.readFileSync('./app/wechat/cert/apiclient_key.pem'),cert: fs.readFileSync('./app/wechat/cert/apiclient_cert.pem'), body: formData}, function (err, response, body) {

            if (!err && response.statusCode == 200) {
                console.log(' \n transfers body:',body);
                var return_code = getXMLNodeValue('return_code', body.toString("utf-8")) || 'FAIL';

                console.log(' \n transfers return_code:%s',return_code);
                if(return_code == 'FAIL'){
                    res.send({code:1,info:'提现的人太多啦,稍后再试吧!'});
                    return;
                }
                var result_code = getXMLNodeValue('result_code', body.toString("utf-8")) || 'FAIL';

                if(result_code.indexOf('FAIL') != -1){
                    res.send({code:1,info:'提现的人忒多啦,稍后再试试哦!'});
                    return;
                }

                userDao.increaseUserCoin(openid,-postCoin, function (err) {
                    if(err){
                        res.send({code:1,info:'扣除金币失败,请重试!!'});
                        return;
                    }else {
                        userDao.recorderCash(sid,openid,mch_billno,postCoin,total_amount);
                        res.send({code:0}); //res.render('jsapipay',{rows:body}); //res.redirect(tmp3[0]); } });
                    }
                });
            }else {
                res.send({code:1,info:'提现的人太多啦,稍后再试吧!'});
            }
        });
    });
};

exports.wxPaySign = function (req,res) {

    var xml = req.body.xml;
    //var xml = body.xml;
    //console.log(' xml:%s, xmls',xml.return_code,JSON.stringify(xml));

    if(xml.return_code == 'SUCCESS' && xml.result_code == 'SUCCESS'){
        var sid = xml.out_trade_no.substring(7,15).replace(/\b(0+)/gi,"");
        userDao.recorderOrders(sid,xml.openid,xml.total_fee,xml.out_trade_no,xml.transaction_id,xml.time_end, function (err) {
            if(!err){
                var coin = tradeConfi(parseInt(xml.total_fee));

                userDao.increaseUserCoin(xml.openid,coin, function (err) {      //加金币到数据库
                    if(err){
                        console.log('充值成功,但是金币加入失败,out_trade_no:%s',xml.out_trade_no);
                        return;
                    }
                    var formData = "<xml>";
                    formData+="<return_code>SUCCESS</return_code>";
                    formData+="<return_msg>OK</return_msg>";
                    formData += "</xml>";
                    res.end(formData);
                });

            }
        });
    }
};


/************ distribution ***************/

exports.disPay = function (req, res) {
    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    var openid = req.headers.disopenid;
    var uid = req.headers.disuid;

    var time_stamp = new Date().getTime();
    var ip = req.ipAddress;
    var bookingNo =padNum(uid,8)+time_stamp;
    //console.log('---openid: %s,uid: %s,ip: %s,bookingNo: %s',openid,uid,ip,bookingNo);
    var attach = 'distribution';
    var nonce_str = createNonceStr(15);
    //console.log(' \n 1. nonce_str: %s',nonce_str);
    //var total_fee = 800;
    var total_fee = 1;
    //console.log('---goodid:%s,total_fee:%s',goodid,total_fee);
    //total_fee = 1;
    var body = '充值会员';
    var dataOpt = {
        appid: wxPayConf.appID,
        attach: attach,
        body: body,
        mch_id: wxPayConf.mch_id,
        nonce_str: nonce_str,
        notify_url:wxPayConf.disNotify_url,
        openid:openid,
        out_trade_no:bookingNo,
        spbill_create_ip:ip,
        total_fee:total_fee,
        trade_type:'JSAPI'
    };
    var formData = "<xml>";
    formData += "<appid>"+wxPayConf.appID+"</appid>"; //appid
    formData += "<attach>"+attach+"</attach>"; //附加数据
    formData += "<body>"+body+"</body>";
    formData += "<mch_id>"+wxPayConf.mch_id+"</mch_id>"; //商户号
    formData += "<nonce_str>"+nonce_str+"</nonce_str>"; //随机字符串，不长于32位。
    formData += "<notify_url>"+wxPayConf.disNotify_url+"</notify_url>";
    formData += "<openid>"+openid+"</openid>";
    formData += "<out_trade_no>"+bookingNo+"</out_trade_no>";
    formData += "<spbill_create_ip>"+ip+"</spbill_create_ip>";
    formData += "<total_fee>"+total_fee+"</total_fee>";
    formData += "<trade_type>JSAPI</trade_type>";
    formData += "<sign>"+wxSignMd5(dataOpt)+"</sign>";
    formData += "</xml>";
    //console.log('\n formData:',JSON.stringify(formData));
    request({url: url, method: 'POST', body: formData}, function (err, response, body) {

        if (!err && response.statusCode == 200) {
            //console.log(' \n res body:',body);
            var return_code = getXMLNodeValue('return_code', body.toString("utf-8")) || 'FALL';

            //console.log(' \n return_code:%s',return_code);
            if(return_code == 'FALL'){
                res.send({code:1,info:'支付失败!'});
                return;
            }
            var result_code = getXMLNodeValue('result_code', body.toString("utf-8")) || 'FALL';
            //console.log(' \n result_code:%s',result_code);
            if(result_code.indexOf('FALL') != -1){
                res.send({code:1,info:'支付失败!'});
                return;
            }

            var prepay_id = getXMLNodeValue('prepay_id', body.toString("utf-8"));
            nonce_str = getXMLNodeValue('nonce_str', body.toString("utf-8"));
            //console.log(' \n 2.nonce_str:%s time_stamp:%s',nonce_str,time_stamp);
            //签名
            var _paySignjs = wxSignMd5({appId: wxPayConf.appID,nonceStr: nonce_str,package:'prepay_id='+prepay_id,signType:'MD5',timeStamp:time_stamp});

            //console.log('prepay_id:%s, _paySignjs:%s,nonce_str:%s,time_stamp:%s',prepay_id,_paySignjs,nonce_str,time_stamp);
            res.send({code:0,prepay_id: prepay_id,_paySignjs:_paySignjs,nonce_str:nonce_str,time_stamp:time_stamp}); //res.render('jsapipay',{rows:body}); //res.redirect(tmp3[0]); } });
        }
    });
};

exports.disWxPaySign = function (req,res) {

    var xml = req.body.xml;
    //var xml = body.xml;
    console.log('xml:%s, xmls',xml.return_code,JSON.stringify(xml));

    if(xml.return_code == 'SUCCESS' && xml.result_code == 'SUCCESS'){
        var uid = xml.out_trade_no.substring(0,8).replace(/\b(0+)/gi,"");
        disUserDao.recorderOrders(uid,xml.openid,xml.total_fee,xml.out_trade_no,xml.transaction_id,xml.time_end, function (err) {
            if(!err){
                //if(parseInt(xml.total_fee) < 800){
                if(!parseInt(xml.total_fee)){
                    console.log('充值金额不够,out_trade_no:%s,Fee:%s',xml.out_trade_no,xml.total_fee);
                }else {
                    disUserDao.setUserVip(xml.openid,function (err) {      //设置为VIP
                        if(err){
                            console.log('充值成功,但是没有成为VIP,out_trade_no:%s',xml.out_trade_no);
                            return;
                        }

                        disUserDao.getUserById(xml.openid,null,null, function (err,user) {
                            if(user){
                                if(user.ref1){       //一级推荐人500分,5元
                                    disUserDao.addCommission(user.ref1,500,xml.openid)
                                }
                                if(user.ref2){
                                    disUserDao.addCommission(user.ref2,50,xml.openid)
                                }
                                if(user.ref3){
                                    disUserDao.addCommission(user.ref3,50,xml.openid)
                                }
                                if(user.ref4){
                                    disUserDao.addCommission(user.ref4,50,xml.openid)
                                }
                                if(user.ref5){
                                    disUserDao.addCommission(user.ref5,50,xml.openid)
                                }
                                if(user.ref6){
                                    disUserDao.addCommission(user.ref6,50,xml.openid)
                                }
                            }
                        });
                    });
                }
                var formData = "<xml>";
                formData+="<return_code>SUCCESS</return_code>";
                formData+="<return_msg>OK</return_msg>";
                formData += "</xml>";
                res.end(formData);
            }
        });
    }
};

exports.disMaPay = function (req, res) {

    var openid = req.headers.disopenid;
    var uid = req.headers.disuid;

    if(!openid || !uid){
        res.send({code:1,info:'必要的参数缺失!'});
        return;
    }

    var id = 12597;    //码支付注册所生成
    var type = 3;      //1：支付宝 2：QQ钱包 3：微信支付。
    var act = 0;       //1:即时到账 0:代收款。
    var price = 10;    //最大值99999.99最小值0.01
    var pay_id = uid;  //唯一标识
    var param = openid;       //自定义参数
    var notify_url = wxPayConf.disMaNotify_url;       //异步通知函数
    var return_url = wxPayConf.disMaReturn_url;       //异步通知函数
    var token = '';         //创建订单令牌,跟sign参数2选1
    var call = '';          //js回调的函数名
    var chart = 'utf-8';    //utf-8或gb2312默认utf-8
    var page = 1;           //付款页面方式:1,2,3,4
    var outTime = 360;      //二维码超时设置(秒) 默认值360
    var pay_type = 0;       //授权支付宝官方接口,1为启用支付宝官方接口,默认0
    var qrcode_url = '';    //默认是云端上传的二维码 自行实现则传该值 如:qrcode.php 会传回参数type=1&money=1&tag=0根据money值可展示本地二维码

    var data = ksort({id:id,type:type,act:act,price:price,pay_id:pay_id,param:param,notify_url:notify_url,return_url:return_url,token:token,call:call,chart:chart,page:page,outTime:outTime,pay_type:pay_type,qrcode_url:qrcode_url}); //重新排序对象 按照首字符开始排序
    var params = "";
    for (var key in data) {
        params +=data[key] == ''?'':key + "=" + data[key] + "&";
    }
    params = params.substring(0, params.length - 1); //去掉最后一个&字符
    var sign = maSignMD5(params+wxPayConf.maSecret);
    //console.log('params:%s,sign:%s',JSON.stringify(params),JSON.stringify(sign));
    var url = "http://codepay.fateqq.com:52888/creat_order/?" + params + '&sign=' + sign; //支付页面
    res.send({code:0,payUrl:url});

};

exports.disMaPaySign = function (req,res) {
    var body = req.body;
    var maSign = body.sign;
    if(body.money < 10){
        res.end('fail');
        return;
    }
    delete body.sign;
    var data = ksort(req.body);
    var params = "";
    for (var key in data) {
        params +=data[key] == ''?'':key + "=" + data[key] + "&";
    }
    params = params.substring(0, params.length - 1);    //去掉最后一个&字符
    var sign = maSignMD5(params+wxPayConf.maSecret);

    if(sign == maSign){
        disUserDao.recorderOrders(body.pay_id,body.param,body.money * 100,body.pay_name,body.pay_no,new Date(body.pay_time * 1000).toLocaleString(),function(err){
            if(err){
                res.end('fail');
            }else {
                disUserDao.setUserVip(body.param,function (err) {      //设置为VIP
                    if (err) {
                        console.log('支付成功,但没有成为会员',body.param);
                        res.end('fail');
                        return;
                    }
                    disUserDao.getUserById(body.param,null,null, function (err,user) {
                        if(!err && user){
                            if(user.ref1 && user.ref1 != '0'){       //一级推荐人500分,5元
                                judgeComi(user.ref1,body.param);
                            }
                        }
                    });
                    res.end('ok');

                });
            }
        });

    }else {
        res.end('fail');
    }
};

exports.disTransfers = function (req, res) {
    var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    var openId = req.headers.disopenid;
    var disCoin =parseInt(req.headers.discoin);

    //if(openId == 'o4AyEtw8BqchrikBbj4XMjfqPuWs' || openId == 'o4AyEt2gypi_z981XBQzM5in0q_U'){
    //    res.send({
    //        code:1,
    //        info:'您暂时无法提现!'
    //    });
    //    return;
    //}

    if(!openId || !disCoin){
        res.send({
            code:1,
            info:'必要的参数缺失!'
        });
        return;
    }

    disUserDao.getTodayCash(openId, function (err,totalCash) {
        if(err || totalCash+disCoin > 5000){
            res.send({
                code:1,
                info:'今日已经超过提现最大限额,明天再来取吧!'
            });
            return;
        }

        //对金币进行处理
        disUserDao.getUserById(openId,null,null, function (err,user) {
            if(err){
                res.send({code:1,info:'获取信息失败!'});
                return;
            }

            if(disCoin>user.coin){
                res.send({code:1,info:'金币不足!'});
                return;
            }

            var ip = req.ipAddress;
            var mch_billno = createNonceStr(15);        //商户订单号
            //console.log('---opid:%s,ip:%s',openId,ip);
            var nonce_str = createNonceStr(15);
            //console.log(' \n 1. nonce_str: %s',nonce_str);
            var total_amount = disCoin;
            //total_amount = 100;
            var check_name = 'NO_CHECK';
            var desc = '发放奖励~~';
            var dataOpt = {mch_appid:wxPayConf.appID,mchid:wxPayConf.mch_id,nonce_str:nonce_str,partner_trade_no:mch_billno,openid:openId,check_name:check_name,amount:total_amount,desc:desc,spbill_create_ip:ip};
            var formData = "<xml>";
            formData += "<amount>"+total_amount+"</amount>";
            formData += "<check_name>"+check_name+"</check_name>";        //校验用户姓名选项
            formData += "<desc>"+desc+"</desc>";        //企业付款描述信息
            formData += "<mch_appid>"+wxPayConf.appID+"</mch_appid>"; //appid
            formData += "<mchid>"+wxPayConf.mch_id+"</mchid>"; //商户号
            formData += "<nonce_str>"+nonce_str+"</nonce_str>"; //随机字符串，不长于32位。
            formData += "<openid>"+openId+"</openid>";
            formData += "<partner_trade_no>"+mch_billno+"</partner_trade_no>"; //商户订单号
            formData += "<spbill_create_ip>"+ip+"</spbill_create_ip>";
            formData += "<sign>"+wxSignMd5(dataOpt)+"</sign>";
            formData += "</xml>";
            //console.log('0 formData:%s \n',formData);
            request({url: url, method: 'POST',key: fs.readFileSync('./app/wechat/cert/apiclient_key.pem'),cert: fs.readFileSync('./app/wechat/cert/apiclient_cert.pem'), body: formData}, function (err, response, body) {

                if (!err && response.statusCode == 200) {
                    //console.log(' \n transfers body:',body);
                    var return_code = getXMLNodeValue('return_code', body.toString("utf-8")) || 'FAIL';

                    //console.log(' \n transfers return_code:%s',return_code);
                    if(return_code == 'FAIL'){
                        res.send({code:1,info:'提现的人太多啦,稍后再试吧!'});
                        return;
                    }
                    var result_code = getXMLNodeValue('result_code', body.toString("utf-8")) || 'FAIL';

                    if(result_code.indexOf('FAIL') != -1){
                        res.send({code:1,info:'提现的人太多啦,稍后再试吧!'});
                        return;
                    }

                    disUserDao.increaseUserCoin(openId,-disCoin, function (err) {
                        if(err){
                            res.send({code:1,info:'扣除金币失败,请重试!!'});
                            return;
                        }else {
                            disUserDao.recorderCash(user.uid,openId,disCoin,total_amount,mch_billno);
                            res.send({code:0}); //res.render('jsapipay',{rows:body}); //res.redirect(tmp3[0]); } });
                        }
                    });
                }else {
                    res.send({code:1,info:'提现的人太多啦,稍后再试吧!'});
                }
            });
        });
    });
};

var judgeComi = function (openId,contributor) {

    disUserDao.getUserById(openId,null,null, function (err,user) {
        if(!err && user){
            if(user.vip == 1) disUserDao.addCommission(openId,500,contributor);     //给一级代理发放5块

            if(user.ref1 && user.ref1 != '0'){
                judgeComi2(user.ref1,contributor);
            }

            if(user.ref2 && user.ref2 != '0'){
                judgeComi2(user.ref2,contributor);
            }

            if(user.ref3 && user.ref3 != '0'){
                judgeComi2(user.ref3,contributor);
            }

            if(user.ref4 && user.ref4 != '0'){
                judgeComi2(user.ref4,contributor);
            }

            if(user.ref5 && user.ref5 != '0'){
                judgeComi2(user.ref5,contributor);
            }

        }
    });
};

var judgeComi2 = function (openId,contributor) {
    disUserDao.getUserById(openId,null,null, function (err,user) {
        if(!err && user) {
            if (user.vip == 1) disUserDao.addCommission(openId, 50, contributor);  //其他级别代理发放5毛
        }
    });
};

//签名算法
function wxSignMd5(dataOpt) {
    //console.log('----dataopt:%s \n',JSON.stringify(dataOpt));
    var string = raw(dataOpt);
    var key = wxPayConf.partnerSecret;
    string = string+'&key='+key;
    var crypto = require('crypto');
    return crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase();
};

//签名算法
function maSignMD5(data,codeBase) {
    var buf = typeof data == "string" ? codeBase == 'utf8' ? iconv.encode(data, 'utf8') : new Buffer(data) : data;
    var str = buf.toString("binary");
    return crypto.createHash("md5").update(str,'utf8').digest("hex");
};


ksort = function (inputArr, sort_flags) { //JS版对象排序
    var tmp_arr = {},
        keys = [],
        sorter, i, k, that = this,
        strictForIn = false,
        populateArr = {};

    switch (sort_flags) {
        case 'SORT_STRING':
            // compare items as strings
            sorter = function (a, b) {
                return that.strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING':
            // compare items as strings, original by the current locale (set with  i18n_loc_set_default() as of PHP6)
            var loc = this.i18n_loc_get_default();
            sorter = this.php_js.i18nLocales[loc].sorting;
            break;
        case 'SORT_NUMERIC':
            // compare items numerically
            sorter = function (a, b) {
                return ((a + 0) - (b + 0));
            };
            break;
        // case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                var aFloat = parseFloat(a),
                    bFloat = parseFloat(b),
                    aNumeric = aFloat + '' === a,
                    bNumeric = bFloat + '' === b;
                if (aNumeric && bNumeric) {
                    return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0;
                } else if (aNumeric && !bNumeric) {
                    return 1;
                } else if (!aNumeric && bNumeric) {
                    return -1;
                }
                return a > b ? 1 : a < b ? -1 : 0;
            };
            break;
    }

    // Make a list of key names
    for (k in inputArr) {
        if (inputArr.hasOwnProperty(k)) {
            keys.push(k);
        }
    }
    keys.sort(sorter);

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js
            .ini['phpjs.strictForIn'].local_value !== 'off';
    populateArr = strictForIn ? inputArr : populateArr;

    // Rebuild array with sorted key names
    for (i = 0; i < keys.length; i++) {
        k = keys[i];
        tmp_arr[k] = inputArr[k];
        if (strictForIn) {
            delete inputArr[k];
        }
    }
    for (i in tmp_arr) {
        if (tmp_arr.hasOwnProperty(i)) {
            populateArr[i] = tmp_arr[i];
        }
    }

    return strictForIn || populateArr;
};

//签名算法
function wxSignSHA256(dataOpt) {
    //console.log('----dataopt:%s \n',JSON.stringify(dataOpt));
    var string = raw(dataOpt);
    var key = wxPayConf.partnerSecret;
    string = string+'&key='+key;
    var crypto = require('crypto');
     var sign = crypto.createHash('sha256').update(string,'utf8').digest('hex').toUpperCase();
    console.log('----dataopt:%s \n sign:%s',JSON.stringify(dataOpt),sign);
    return sign;
};

//签名时候的参数处理
function raw(args) {
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key] = args[key];
    });

    var string = '';
    for (var k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
};

function createNonceStr(len) {
    return Math.random().toString(36).substr(2, len);
};

function getOrderId(goodid,sid){

    //5位随机数  //商品号2位  //sid 8位
    return createNonceStr(5)+'0'+goodid+padNum(sid,8);
}

/**
 * 通过商品ID得到应付金额
 * @param goodid 商品ID
 * @returns {number}  金额(分)
 */
function goodConfi(goodid) {
    switch (goodid){
        case 1:
            return 550;  //5.5元 550分
            break;
        case 2:
            return 1000;  //10元 1000分
            break;
        case 3:
            return 2000;  //20元 2000分
            break;
        case 4:
            return 3000;  //30元 3000分
            break;
        case 5:
            return 5000;  //50元 5000分
            break;
        case 6:
            return 9000;  //90元 9000分
            break;
        default:
            return 550;  //5.5元 550分
    }
}

/**
 * 通过支付金额得到欢乐币数量
 * @param totalFee
 * @returns {number}
 */
function tradeConfi(totalFee) {
    switch (totalFee){
        case 550:
            return 5;  //5元
            break;
        case 1000:
            return 10;  //10元
            break;
        case 2000:
            return 22;  //20元 2000分
            break;
        case 3000:
            return 33;  //30元 3000分
            break;
        case 5000:
            return 55;  //50元 5000分
            break;
        case 9000:
            return 100;  //90元 9000分
            break;
        default:
            return 5;  //5元金币
    }
}

/**
 * 欢乐币兑RMB比例
 * @param postCoin
 * @returns {number}
 */
function cashConfi(postCoin) {
    switch (postCoin){
        case 11:
            return 100;  //5元
            break;
        case 12:
            return 500;  //5元
            break;
        case 20:
            return 1000;  //10元
            break;
        case 28:
            return 2000;  //20元 20000分
            break;
        case 37:
            return 3000;  //30元 30000分
            break;
        case 56:
            return 5000;  //50元 50000分
            break;
        case 101:
            return 9000;  //90元 90000分
            break;
    }
}

/**
 * 补全位数
 * @param num  需要补全的数
 * @param n    期望长度
 * @returns {*}
 */
function padNum(num, n) {
    var len = num.toString().length;
    while(len < n) {
        num = "0" + num;
        len++;
    }
    return num;
}

//解析XML
function getXMLNodeValue(node_name,xml){
    try {
        var tmp = xml.split("<"+node_name+">");
        var _tmp = tmp[1].split("</"+node_name+">");
        return _tmp[0].split('[')[2].split(']')[0];
    }catch (err){
        console.log('解析xml失败:%s,node_name:%s',err,node_name);
        return 'FALL';
    }
};




